package com.tju.Controller.user;

import com.alibaba.fastjson.JSON;
import com.tju.Model.RoleType;
import com.tju.Model.User;
import com.tju.Util.EncryptionUtil;
import com.tju.Util.ResultDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.tju.Service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * Created by Boyu on 2017/2/22.
 */

@Slf4j
@Controller
@RequestMapping("/user")
public class UserFunctionController {

    @Resource
    UserService userServiceImpl;

    @Value("${image.uploadPath}")
    String uploadPath; //文件上传目录

    @RequestMapping(value = "/upload")
    public String user(HttpServletRequest request, Model model) {
        log.info("user upload page");

        return "user/upload";
    }

    /**
     * 添加新的用户
     * @param userInfoForm
     * @param request
     * @return
     */
    @RequestMapping(value="/insertUser", method=RequestMethod.POST)
    @ResponseBody
    public String addUser(User userInfoForm, HttpServletRequest request){
        ResultDO<Boolean> booleanResultDO = new ResultDO<>();
        try {
            User new_user = new User();
            new_user.setUserPwd(EncryptionUtil.getHash(userInfoForm.getUserPwd(), "MD5"));
            new_user.setDatetime(new Date());
            return JSON.toJSONString(userServiceImpl.insertNewUser(new_user, RoleType.ROLE_USER));
        } catch (Exception e) {
            log.error("增加新用户失败，params：{}", userInfoForm.toString());
            booleanResultDO.setErrorCode("增加用户失败，请重试");
        }
        return JSON.toJSONString(booleanResultDO);
    }


    /**
     * 上传用户头像
     * @param userId
     * @param myfiles
     * @param request
     * @return
     * @throws IOException
     *
     *
     * note 如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
       如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解并且上传多个文件时，
       前台表单中的所有<input type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
     *
     */
    @RequestMapping(value="/uploadFiles", method=RequestMethod.POST)
    @ResponseBody
    public String addUser(int userId,@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
        ResultDO<Boolean> booleanResultDO = new ResultDO<>();

        try{
            for(MultipartFile myfile : myfiles){
                if(myfile.isEmpty()){
                    System.out.println("文件未上传");
                }else{
                    log.info("文件长度: " + myfile.getSize());
                    log.info("文件类型: " + myfile.getContentType());
                    log.info("文件名称: " + myfile.getName());
                    log.info("文件原名: " + myfile.getOriginalFilename());

                    //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
                    String realPath = request.getSession().getServletContext().getRealPath(uploadPath);

                    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath,getRandomFileName(myfile)));
                }
            }
        }catch (Exception ex)
        {
            booleanResultDO.setErrorCode("文件上传失败请重试");
        }
        booleanResultDO.setSuccess(true);
        return JSON.toJSONString(booleanResultDO);
    }

    private String getRandomFileName(MultipartFile uploadFile)
    {
       //获取文件后缀名
        String extensionName = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf("."));
       //获取当前时间戳
        String timeName = System.currentTimeMillis()+new Random().nextInt(99999)+extensionName;
        return timeName;
    }

}
